/*
 * User.cpp
 *
 *  Created on: May 3, 2011
 *      Author: scolinas
 */

#include "User.h"

User::User(string user_file, bool debug) {
	this->user_file = user_file;
	this->log = Logger::Instance(debug);
	this->lock = new LockFile(user_file.c_str(), debug);
}

User::~User() {
	delete lock;
}

bool User::entrar_al_chat(string alias) {
	std::ifstream file(this->user_file.c_str());
	string line;
	while (std::getline(file, line)) {
		if (line.find("|" + alias + "|") != string::npos) {
			//Si ya existe un usuario con ese alias
			return false;
		}
	}
	this->alias = alias;
	this->log->writeToLogFile(this->alias + " ingresando en la sala de chat\n");
	this->lock->tomarLock();
	string userToBeAdd = "|" + this->alias + "|";
	this->lock->escribir(userToBeAdd.c_str(), userToBeAdd.size());
	this->lock->liberarLock();
	this->log->writeToLogFile(this->alias + " ingresó en la sala de chat\n");
	return true;
}

int User::salir_del_chat() {
	// eliminar usuario del archivo ¿es atomico?
	this->log->writeToLogFile(this->alias + " saliendo de la sala de chat\n");
	this->lock->tomarLock();
	string line;
	std::ifstream file(this->user_file.c_str());
	std::getline(file, line);
	int pos_ini = line.find("|" + this->alias + "|");
	line = line.erase(pos_ini, this->alias.size() + 2);
	this->lock->reemplazar(line.c_str(), line.size());
	this->lock->liberarLock();
	this->log->writeToLogFile(this->alias + " salió de la sala de chat\n");
	return line.size();
}

string User::get_alias() {
	return this->alias;
}
